package com.wwgsky.basestatusfragment.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import com.wwg.module_base.impl.PageState_Impl
import com.wwg.module_base.inter.PageState_Inter
import com.wwgsky.basestatusfragment.R

/**
 * 自带状态提示页的 Fragment 基类
 */
abstract class BaseStateFragment : LazyFragment4DB() {

    private var pageState_Control: PageState_Inter? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        //获取根布局
        val root_frameLayout = FrameLayout(requireActivity())
        //获取状态页布局
        val layout_state = View.inflate(context, R.layout.fragment_states, null)
        //设置布局参数
        val layout_params = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT
        )
        //设置布局
        layout_state.layoutParams = layout_params
        //获取继承者根布局
        val rootView = getLayoutView(inflater, container, false)
        //往根布局中添加继承者根布局和状态页布局
        root_frameLayout.addView(rootView)
        root_frameLayout.addView(layout_state)
        //根据状态页初始化状态接口
        initStateView(layout_state)
        initView(rootView)

        return root_frameLayout
    }

    /**
     * 根据状态页初始化状态接口
     */
    private fun initStateView(view: View): View {

        //获取 加载异常 状态页
        val stateImg = view.findViewById<AppCompatImageView>(R.id.fragmentStates_img)
        //获取 加载异常 状态页
        val stateTxt = view.findViewById<AppCompatTextView>(R.id.fragmenStates_txt)

        //实例化页面状态控制接口
        pageState_Control = PageState_Impl(
            view,
            stateImg,
            stateTxt
        )

        return view

    }

    /**
     * 开始加载
     */
    fun startLoad(msg: String) {
        pageState_Control?.showState(BaseStatusConfig.ResId_Loading, msg)
    }

    /**
     * 加载结束
     */
    fun loadFinish() {
        pageState_Control?.loadFinish()
    }

    /**
     * 加载异常
     */
    fun showLoadError(msg: String) {
        pageState_Control?.showState(BaseStatusConfig.ResId_Error, msg)
        pageState_Control?.onClickState { onClickState() }
    }

    /**
     * 无网络
     */
    fun showNoNet(msg: String) {
        pageState_Control?.showState(BaseStatusConfig.ResId_NoNet, msg)
    }

    /**
     * 无数据
     */
    fun showNoValue(msg: String) {
        pageState_Control?.showState(BaseStatusConfig.ResId_NoValue, msg)
        pageState_Control?.onClickState { onClickState() }
    }

    /**
     * 状态页面的点击事件
     */
    open fun onClickState() {}

}